package com.whu.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.whu.aircraft.R;
import com.whu.aircraft.User;
import com.whu.dao.interfaces.UserDao;
import com.whu.service.impl.UserService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    final UserService userService;
    final UserDao userDao;
    public UserController(UserService userService,UserDao userDao){
        this.userService = userService;
        this.userDao = userDao;
    }
    @RequestMapping("/user/login")
    public R login(@RequestBody User user){
        User u_data = userDao.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUsername,user.getUsername())
                .eq(User::getPassword,user.getPassword()));
        if(u_data==null){
            return R.error(-1,"用户名或密码错误");
        }
        return R.ok().put("user",u_data);
    }
    @RequestMapping("/user/register")
    public R register(@RequestBody User user){
        User u_data = userDao.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername,user.getUsername()));
        if(u_data!=null){
            return R.error(-1,"用户名重复");
        }
        if(user.getPassword()==null||user.getPassword().equals("")){
            user.setPassword("123456");
        }
        userService.create(user);
        return R.ok();
    }
    @RequestMapping("/user/listByPage/{page}")
    public R listByPage(@PathVariable int page){
        IPage<User> iPage = userService.listWithPage(page,1);
        return R.ok().put("userList",iPage.getRecords())
                .put("pageCnt",iPage.getPages());
    }
    @RequestMapping("/user/list")
    public R list(){
        List<User> list = userService.list();
        return R.ok().put("userList",list);
    }
    @RequestMapping("/user/update")
    public R update(@RequestBody User user){
        userService.update(user);
        return R.ok("更新成功");
    }
    @RequestMapping("/user/delete/{id}")
    public R delete(@PathVariable Long id){
        userService.delete(id);
        return R.ok("删除成功");
    }




}
